<?php
//error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING & ~E_CORE_WARNING);	
error_reporting(E_ERROR);
//error_reporting(0);

use Workerman\Worker;
//use \Workerman\Lib\Timer;
require_once __DIR__ . '/Workerman/Autoloader.php';

Worker::$stdoutFile = '/test.log';

$myconn=dwopendb();

$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
$result=mysql_query($strSql,$myconn);
$dbResult = mysql_fetch_array($result);
if($dbResult[0])
{
	$TCPserver = "tcp://0.0.0.0:".$dbResult[0];
}else
{
	$TCPserver = "tcp://0.0.0.0:1119";
}
@mysql_free_result($result);
dwclosedb($myconn);

$http_worker = new Worker($TCPserver);

$http_worker->count = 1;

$http_worker->uidConnections = array();

$http_worker->onMessage = function($connection, $data)
{
	global $http_worker;

	$deresult=$data;
	var_dump($data);

	$indexA=strpos($deresult,'{');   
	$indexB=strpos($deresult,'}');	
	$deresultJson=substr($deresult,$indexA,$indexB-$indexA+1);
//	file_put_contents("test.log","deresultJson:".$deresultJson."\n", FILE_APPEND);
	$deresultArr=json_decode($deresultJson,true);
//	file_put_contents("test.log","[device_id]:".$deresultArr["device_id"]."\n", FILE_APPEND);
//	$dwclient=$deresultArr["dwclient"];
//	file_put_contents("test.log","  data: ".$data." LINE: ".__LINE__ ."\n", FILE_APPEND);
	if(@$deresultArr["HeaderStx"] && @$deresultArr["device_id"])
	{
		if($deresultArr["PacketType"]=="01")
		{
			$dwuid=$deresultArr["device_id"];
			if(!isset($connection->uid))
			{
				$connection->uid = $dwuid;
				$http_worker->uidConnections[$connection->uid] = $connection;
	//			file_put_contents("test.log", $deresultArr["device_id"]."\n", FILE_APPEND);			
			}		
			sendMessageByUid($dwuid,$data);
//			file_put_contents("test.log","{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}".$dwuid."\n", FILE_APPEND);			
			file_put_contents("test.log","\n dwuid: ".$dwuid." data ".$data." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["PacketType"]=="02")
		{
			$dwuid=$deresultArr["device_id"];			
			sendMessageByUid($dwuid,$data);
//			file_put_contents("test.log","{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}".$dwuid."\n", FILE_APPEND);			
			file_put_contents("test.log","\n dwuid: ".$dwuid." data ".$data." LINE: ".__LINE__ ."\n", FILE_APPEND);
/*			$data="{\"HeaderStx\":\"EB\", \"dwdevice\":\"DAWU\" ,\"trans_id\":\"".uuid()."\",\"PacketType\":\"02\", \"Data\" : \"00\", \"EndText\" : \"03\"}";
			sendMessageByUid($dwuid,$data);
			file_put_contents("test.log","\n dwuid: ".$dwuid." data ".$data." LINE: ".__LINE__ ."\n", FILE_APPEND);*/
		}
	}
	if(@$deresultArr["dwclient"])
	{
		//"{\"result\":\"OK\",\"pass\":\"access\",\"userid\":\"$renyuanjieguoji[1]\",\"departmentname\":\"$renyuanjieguoji[2]\",\"name\":\"$renyuanjieguoji[3]\",\"yinpin\":\"yp01\",\"shipin\":\"sp01\",\"anjian\":\"kaishi\"}";
		$dwuid=$deresultArr["dwdevice"];
		$gonghao = $deresultArr["dwclient"];
		$departmentname  = $deresultArr["departmentname"];
		$staffname = $deresultArr["staffname"];
		$menghao = $deresultArr["gatenum"];
		$shibieshijian = $deresultArr["shibieshijian"];
		
		if($deresultArr["dwcmd"]=="rlok")
		{
//			sendMessageByUid($dwuid,"{\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}");
//			sendMessageByUid($dwuid,"{\"dwdevice\":\"".$dwuid."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}");
			$cmd="{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_RLFANGXING\",\"menghao\":\"$menghao\",\"gonghao\":\"$staffname\",\"staffname\":\"$menghao\",\"departmentname\":\"$departmentname\",\"shibieshijian\":\"$shibieshijian\"}";
			sendMessageByUid($dwuid,$cmd);
//			file_put_contents("test.log","{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}".$dwuid."\n", FILE_APPEND);			
			file_put_contents("test.log","dwuid: ".$dwuid." cmd: ".$cmd." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["dwcmd"]=="rlbaojing")
		{
			$cmd="{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_RLBAOJING\",\"menghao\":\"$menghao\",\"gonghao\":\"$staffname\",\"staffname\":\"$menghao\",\"departmentname\":\"$departmentname\",\"shibieshijian\":\"$shibieshijian\"}";
			sendMessageByUid($dwuid,$cmd);
			file_put_contents("test.log","dwuid: ".$dwuid." cmd: ".$cmd." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["dwcmd"]=="xbaojing")
		{
			sendMessageByUid($dwuid,"{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_XBAOJING\",\"menghao\":\"$menghao\",\"gonghao\":\"$staffname\",\"staffname\":\"$menghao\",\"departmentname\":\"$departmentname\",\"shibieshijian\":\"$shibieshijian\"}");
		}
		if($deresultArr["dwcmd"]=="opendoor1")
		{
//			sendMessageByUid($dwuid,"{\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}");
//			sendMessageByUid($dwuid,"{\"dwdevice\":\"".$dwuid."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}");
			sendMessageByUid($dwuid,"{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}");
//			file_put_contents("test.log","{\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_OPENCLOSE\",\"gatenum\":\"0\"}".$dwuid."\n", FILE_APPEND);			
//			file_put_contents("test.log","\n dwuid: ".$dwuid."\n", FILE_APPEND);
		}
	}
	else if(@$deresultArr["dwdevice"] && @$deresultArr["trans_id"])
	{
		$dwuid=$deresultArr["dwdevice"];
//		var_dump($dwuid);
		if($deresultArr["cmd_code"]=="DW_OPENCLOSE")
		{
			sendMessageByUid($dwuid,$data);
			file_put_contents("test.log", $data." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["cmd_code"]=="DW_CHANGKAI")
		{
			sendMessageByUid($dwuid,$data);
//			file_put_contents("test.log", $data." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["cmd_code"]=="DW_UPDATE_USERINFO")
		{
			sendMessageByUid($dwuid,$data);
//			file_put_contents("test.log", $data." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
		if($deresultArr["cmd_code"]=="DW_SET_DEVICEINFO")
		{
			sendMessageByUid($dwuid,$data);
//			file_put_contents("test.log", $data."\n", FILE_APPEND);
		}
		
		if($deresultArr["cmd_code"]=="DW_DELETE_USERINFO")
		{
			sendMessageByUid($dwuid,$data);
//			var_dump($deresultArr["cmd_code"]);
//			file_put_contents("test.log", $data." LINE: ".__LINE__ ."\n", FILE_APPEND);
		}
	}
	else if(@$deresultArr["device_id"] && @$deresultArr["time"])
	{
		if(!isset($connection->uid))
		{
//			$connection->uid = $_GET["device_id"];
			$connection->uid = $deresultArr["device_id"];
			$http_worker->uidConnections[$connection->uid] = $connection;
//			file_put_contents("test.log", $deresultArr["device_id"]."\n", FILE_APPEND);			
		}
		if(abs(strtotime($deresultArr["time"]) - strtotime(date('YmdHis')))>180)
		{
//			sendMessageByUid($dwuid,"{\"cmd_code\":\"DW_UPDATETIME\",\"time\":\"".date('YmdHis')."\"}");
			sendMessageByUid($deresultArr["device_id"],"{\"cmd_code\":\"DW_UPDATETIME\",\"time\":\"".date('YmdHis')."\"}");
		}
//		Timer::add(1,sendcmd ,array($deresultArr["device_id"]) ,true);
//		Timer::add(25,sendcmd ,array($deresultArr["device_id"]) ,true);
		updatestat($deresultArr["device_id"],$deresultArr["ip"],$deresultArr["port"]);
	}else
	{
		
	}	
};

// 当有客户端连接断开时
$http_worker->onClose = function($connection)
{
    global $http_worker;
    if(isset($connection->uid))
    {
        // 连接断开时删除映射
        unset($http_worker->uidConnections[$connection->uid]);
    }
};

// 向所有验证的用户推送数据
function broadcast($message)
{
   global $http_worker;
   foreach($http_worker->uidConnections as $connection)
   {
        $connection->send($message);
   }
}

// 针对uid推送数据
function sendMessageByUid($uid, $message)
{
    global $http_worker;
    if(isset($http_worker->uidConnections[$uid]))
    {
        $connection = $http_worker->uidConnections[$uid];
        $connection->send($message);
		file_put_contents("test.log","uid: ".$uid."  message: ". $message." LINE: ".__LINE__ ."\n", FILE_APPEND);
    }else
	{
		file_put_contents("test.log", $uid." is offline "." LINE: ".__LINE__ ."\n", FILE_APPEND);
	}
}

function delcmd($uid,$trans_id)
{
	$myconn=dwopendb();
	$strSql="DELETE FROM cmdform WHERE transid = \"".$trans_id."\";";
//	file_put_contents("test.log", $strSql."\n", FILE_APPEND);
	$result=mysql_query($strSql,$myconn);
//	}
	@mysql_free_result($result);
	dwclosedb($myconn);
}

function sendcmd($uid)
{
	$myconn=dwopendb();
	$strSql="SELECT cmdstr FROM cmdform WHERE controlerNum = \"".$uid."\";";
//	file_put_contents("test.log", $strSql."\n", FILE_APPEND);
	$result=mysql_query($strSql,$myconn);
	$strSql="[";
	$i=0;	
	while(($dbResult = mysql_fetch_array($result)) && ($i<10))
	{
		$strSql .=$dbResult[0].",";
		$i++;
	}
	if($i==0)
	{
		$strSql .= "]";
	}else
	{
		$strSql = substr_replace($strSql,"]",-1,1);
	}
//		file_put_contents("test.log", "strSql =".$strSql, FILE_APPEND);
	sendMessageByUid($uid, $strSql);
//	}
	@mysql_free_result($result);
	dwclosedb($myconn);
}

function updatestat($uid,$ip,$port)
{
	$strSql="SELECT MAX(skid) FROM gatesetting WHERE controlerNum = \"".$uid."\";";
	$myconn=dwopendb();
	$result=mysql_query($strSql,$myconn) or die(mysql_error());
	$dbResult = mysql_fetch_array($result) or die(mysql_error());
//		$string = "\n strSql:".$strSql."result : ".$dbResult[0]."\n";
//		file_put_contents("test.log", $string, FILE_APPEND);
	@mysql_free_result($result);

	$strSql="UPDATE gatesetting SET lianjie= 'no';";
	$result=mysql_query($strSql,$myconn);

	if($dbResult[0])
	{
		$strSql="UPDATE gatesetting SET lianjie= 'online',lasttime='".date('Y-m-d H:i:s')."',IP='".$ip."',PORT='".$port."' WHERE controlerNum = '".$uid."';";
		$result=mysql_query($strSql,$myconn);
		@mysql_free_result($result);
//		$string = "\n strSql:".$strSql."\n";
//		file_put_contents("test.log", "strSql:".$strSql." line: ".__LINE__."\n", FILE_APPEND);
	}else
	{
		for($i=0;$i<4;$i++)
		{
			//$strSql="INSERT INTO gatesetting(controlerNum,IP,PORT,lianjie,lasttime,gatenum) VALUES('".$uid."','".$ip."','".$port."','online','".date('Y-m-d H:i:s')."','$i');";
			$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,region,controlmethod,delayopentime, delayclosetime,sensorstat,readerfunction,attendancecheck,password,forcepass,antipassback,serverIP,serverPORT,realtimepath,CameraADDR,CameraPORT,CameraRTSP,jianquanfangshi,sVersion,IP,PORT,lianjie,lasttime) VALUES('$uid','$i','大门','总部','card','0','0','NG','26','yes', '123456','999999','no','127.0.0.1','80','/dwrealtime.php','127.0.0.1','80','127.0.0.1','jizhong','2018V11.28P2P_fxc','$ip','$port','online','".date('Y-m-d H:i:s')."');";
			$result=mysql_query($strSql,$myconn);
			@mysql_free_result($result);
		}
//		$string = "strSql:".$strSql."\n";
		file_put_contents("test.log", "strSql:".$strSql." line: ".__LINE__."\n", FILE_APPEND);
	}			
	dwclosedb($myconn);
}

function dwclosedb($myconn)
{
	mysql_close($myconn);	
}

function dwopendb()
{
#	$myconn=@mysql_connect("localhost","root","dawu");
        $myconn=@mysql_connect("localhost","dw","DWdawu-309");
	if(!$myconn)
	{
		die('Could not connect: '.mysql_error());
		$string = "Can't connect database : ".mysql_error();
		file_put_contents("test.log", $string, FILE_APPEND);
		return;
	}
//	$db_selected=mysql_select_db("dwzuapairenlian",$myconn);
	$db_selected=mysql_select_db("dwzuapairenlian",$myconn);
	if(!$db_selected)
	{
		die("Can't use database dwzuapairenlian : ".mysql_error());
		$string = "Can't use database : ".mysql_error();
		file_put_contents("test.log", $string, FILE_APPEND);		
		mysql_close($myconn);
		return;
	}
	return $myconn;
}

function uuid() 
{
	if (function_exists('com_create_guid')) 
	{
		return md5(com_create_guid());
	}else 
	{
		mt_srand((double)microtime()*10000);                   //optional for php 4.2.0 and up.
		$charid = md5(uniqid(rand(),true)); 
//            $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); 
//            $hyphen = chr ( 45 );                                          // "-"
//            $uuid = '' .                                                   //chr(123)// "{"
//            substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );                                                                           //.chr(125);// "}"
		return $charid;
	}
}

// 运行worker
Worker::runAll();
